package com.dsl.tms.service;

import com.dsl.tms.annotation.LoginRequired;
import com.dsl.tms.entity.db.Db;
import com.dsl.tms.entity.redis.AdminRedis;
import com.dsl.tms.entity.request.DbSourse;
import com.dsl.tms.entity.result.Result;
import com.dsl.tms.enums.AppResult;
import com.dsl.tms.repository.DataSourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import javax.transaction.Transactional;
import java.sql.Date;
import java.util.HashMap;

@Service
public class DataSourceService {

    @Autowired
    private DataSourceRepository dataSourceDao;

    @Autowired
    private RedisTemplate redisTemplate;

    private static Logger LOGGER = LoggerFactory.getLogger(DataSourceService.class);


    public HashMap getDataSourceList(String token,DbSourse keywords){
        HashMap responseMap = new HashMap();
        Result result = new Result();
        try {
            Pageable pageable = new PageRequest(keywords.getCurrentPage() - 1,keywords.getPageSize());
            Page<Db> page = dataSourceDao.queryAllWithKeywords(keywords, pageable);
            responseMap.put("dataSourceList",page.getContent());
            responseMap.put("dataSourceCount",page.getTotalElements());
            result.setCode(AppResult.SECCESS.getCode());
            result.setDescription(AppResult.SECCESS.getDescription());
        }catch (Exception e){
            result.setCode(AppResult.FAIL.getCode());
            result.setDescription(AppResult.FAIL.getDescription()+": "+e.getMessage());
            LOGGER.error(e.getMessage(),e.getCause());
        }
        responseMap.put("result",result);
        return responseMap;
    }

    @LoginRequired
    @Transactional
    public HashMap saveDataSource(String token,DbSourse dbSourse){
        HashMap responseMap = new HashMap();
        Result result = new Result();
        try {
            Db db = new Db();
            db.setId(dbSourse.getId());
            db.setDbName(dbSourse.getDbName());
            db.setDriverClassName(dbSourse.getDriverClassName());
            db.setUrl(dbSourse.getUrl());
            db.setOfGroup(dbSourse.getOfGroup());
            db.setUsername(dbSourse.getUsername());
            db.setPassword(dbSourse.getPassword());
            AdminRedis adminRedis = (AdminRedis) redisTemplate.opsForValue().get(token);
            Date now = new Date(new java.util.Date().getTime());
            if (ObjectUtils.isEmpty(db.getId()) || db.getId() == 0 ){
                db.setAdddate(now);
                db.setAddwho(adminRedis.getUserId()+"");
                dataSourceDao.save(db);
            }else {
                db.setEditdate(now);
                db.setEditwho(adminRedis.getUserId()+"");
                dataSourceDao.updateOne(db);
            }

            result.setCode(AppResult.SECCESS.getCode());
            result.setDescription(AppResult.SECCESS.getDescription());
        } catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setCode(AppResult.FAIL.getCode());
            result.setDescription(AppResult.FAIL.getDescription());
            LOGGER.error(e.getMessage());
        }
        responseMap.put("result",result);
        return responseMap;
    }

    @Transactional
    @LoginRequired
    public HashMap deleteDataSource(String token,int id){
        HashMap responseMap = new HashMap();
        Result result = new Result();
        try {
            dataSourceDao.delete(id);
            result.setCode(AppResult.SECCESS.getCode());
            result.setDescription(AppResult.SECCESS.getDescription());
        } catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setCode(AppResult.FAIL.getCode());
            result.setDescription(AppResult.FAIL.getDescription());
        }
        responseMap.put("result",result);
        return responseMap;
    }

}
